package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


@Slf4j
@Component("1003")
public class VipStrategy implements ItemTypeStrategy {
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    /**
     * 处理购买项目类型为：vip会员
     * @param userPaidRecordVo
     */
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理项目类型为：vip会员");
        // 购买vipuser_vip_service 可能需要续期
        // 获取购买时长 vip_service_config. id
        Long vipServiceId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceId);
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        // 保存数据
        UserVipService userVipService = new UserVipService();
        // 赋值
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        Date currenttime = new Date();
        userVipService.setStartTime(currenttime);
        // 过期时间：第一种情况：第一次购买;第二种情况：续期
        // 判端当前用户是否是vip确定续期还是购买
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        if(userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(currenttime)){
            // vip且未过期，续期
//                LocalDateTime localDateTime= new LocalDateTime();
//                Date expireTime = localDateTime.plusMonths(serviceMonth).toDate();
//                System.out.println("过期时间"+expireTime);
//                userVipService.setExpireTime(expireTime);
            currenttime = userInfo.getVipExpireTime();
        }
        //创建对象
        LocalDateTime localDateTime = new LocalDateTime(currenttime);
        // 获取过期时间
        Date expiretime = localDateTime.plusMonths(serviceMonth).toDate();
        // 设置过期时间
        userVipService.setExpireTime(expiretime);
        // 保存数据
        userVipServiceMapper.insert(userVipService);
        // 修改用户vip标识
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(expiretime);
        userInfoMapper.updateById(userInfo);
    }
}
